// step1. open app
require('child_process').exec("cd ../ai-peilian-darwin-x64 && open -a ai-peilian.app");

// setp2. connect to app(wait for app ready)
const WebSocket = require('ws');
let ws = null;

function testWebSocket() {
    ws = new WebSocket('ws://localhost:9999');
    ws.onopen = function (e) {
        console.log('onopen');

        // step3. cmd test
        test();
    };

    ws.onclose = function (e) {
        console.log('onclose');
    };

    ws.onerror = function (e) {
        console.log('onerror');

        if (e.error.code === 'ECONNREFUSED') {
            setTimeout(testWebSocket, 100);
        }
    };

    function test() {
        openUrl('https://lab.1tai.com');
        fullscreen(true);
        setTimeout(function () {
            // close();
        }, 3000);
    }
}
setTimeout(testWebSocket, 100);


/**
 * json格式控制命令
 * 1. 打开链接:
 * {
 *     "cmd": "openurl",
 *     "url": "url"
 * }
 *
 * 2. 琴键消息
 * {
 *     "cmd": "piano",
 *     "msg: "msg"
 * }
 */
function cmd(cmdObj) {
    ws.send(JSON.stringify(cmdObj));
}

function openUrl(url) {
    cmd({
        cmd: 'openurl',
        url: url,
    });
}

function fullscreen(flag) {
    cmd({
        cmd: 'fullscreen',
        flag: flag,
    });
}

function close(flag) {
    cmd({
        cmd: 'close'
    });
}
